﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0" />
    <title>质保书查询</title>


    <link href="./css/da_css.css" rel="stylesheet" type="text/css" />
   <link href="./css/bootstrap.min.css" rel="stylesheet">


    <style>

        /*#dataContainer
        {
            display: flex;
            flex-wrap: wrap;
        }*/


        .control-panel {
            padding: 15px;
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
        }

        .batch-control {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .select-all {
            margin-left: 20px;
            margin-right: 0px;
            width: 20px;
            height: 20px;
        }

        .batch-download-btn {
            background: #43a047;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            margin-right: 20px;
        }

            .batch-download-btn:disabled {
                background: #ccc;
                cursor: not-allowed;
                margin-right: 20px;
            }


        .record {
        }

        .record-top {
            margin: 0px 5px 5px 5px;
            padding: 0px;
            border-top: 1px solid #ccc;
            height: 30px;
            line-height: 30px;
            font-weight: 600;
        }

        .record-bot {
            margin: 5px;
            padding: 0px;
            height: 30px;
            line-height: 30px;
            font-size: 11pt;
            font-weight: 300;
        }

        .hidden {
            display: none;
        }

        .item-id1A {
            display: block;
            float: left;
            width: 50%;
            font-size: 11pt;
            margin: 0px;
            padding-left: 0px;
            /*border-radius: 5px;*/
            /*background-color: #d3d3d3;*/
            text-align: center;
            /*border: 1px solid #ccc;*/
        }

        .item-id1B {
            display: block;
            float: left;
            width: 25%;
            font-size: 11pt;
            margin: 0px;
            padding-left: 0px;
            /*border-radius: 5px;*/
            /*background-color: #d3d3d3;*/
            text-align: center;
            /*border: 1px solid #ccc;*/
        }

        .file-checkbox {
            margin-right: 15px;
            width: 20px;
            height: 20px;
        }


        .item-id2A {
            display: block;
            float: left;
            width: 50%;
            margin: 0px;
            padding-left: 0px;
            text-align: center;
        }


        .item-id2B {
            display: block;
            float: left;
            width: 25%;
            margin: 0px;
            padding-left: 0px;
            text-align: center;
        }

        .download-btn {
            background: #1e88e5;
            color: white;
            border: none;
            padding: 1px 18px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            text-decoration: none;
        }

        .viewload-btn {
            background: #1e88e5;
            color: white;
            border: none;
            padding: 1px 18px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            text-decoration: none;
        }

        #Label_note {
            display: block;
            width: 90%;
            padding: 10px;
            text-align: center;
        }


        .item_last {
            clear: both;
        }


        /* 加载动画的样式 */
        #loading {
            display: none; /* 初始时隐藏 */
            position: fixed; /* 固定位置 */
            left: 50%; /* 水平居中 */
            top: 50%; /* 垂直居中 */
            transform: translate(-50%, -50%); /* 精确居中 */
            font-size: 24px; /* 字体大小 */
            color: #fff; /* 文字颜色 */
            background-color: rgba(0, 0, 0, 0.75); /* 背景颜色和透明度 */
            padding: 20px; /* 内边距 */
            border-radius: 10px; /* 圆角 */
        }

        input[type="text"], textarea {
            height: 32px;
            line-height: 32px;
            width: 99%;
            border: none;
            border-bottom: 1px solid; /* 蓝色实线边框 */
            padding: 10px 5px 3px 10px; /* 内边距 */
            font-size: 16px; /* 字体大小 */
            outline: none; /* 移除默认的聚焦边框 */
        }

        .input_btn {
            height: 38px;
            line-height: 38px;
            font-size: 14pt;
            font-weight: 500;
            width: 100%;
            border-radius: 5px;
        }
    </style>




    <script src="js/pulicCommon.js"></script>

    <script type="text/javascript">

        // 配置下载器-----------------------------------------------------------------begin
        const common = new PulicCommon({
            apiBaseUrl: '/api'
        });


        //授权检查；-------------------------------
        const currentUrl = window.location.href;
        try {
                const result = common.checkAuth(currentUrl);
                console.log('权限认证结果:', result);
        }
        catch (error) {

            console.log('登录不合法: ' + error.message);

            showError('登录不合法: ' + error.message);
        }
        //---------------------------------------------------------------------------------end




    </script>




</head>

<body>
    <form id="form1" runat="server">

        <div id="loading">
            <div class="spinner"></div>
            <div class="spinner_text">
                请稍后，玩命加载数据中......
            </div>
        </div>



        <div>
        </div>
        <div>

            <table border="0" style="width:95%;margin:auto">

                <tr>
                    <td style="width:20%;text-align:right">磅单号</td>
                    <td style="width:30%">  <input type="text" id="TextBox_pound_no" class="form-control" /> </td>
                    <td style="width:20%;text-align:right">车船号</td>
                    <td style="width:30%"><input type="text" id="TextBox_wagon_no" class="form-control" /> </td>
                </tr>
                <tr>
                    <td style="text-align:right">合同号</td>
                    <td>  <input type="text" id="TextBox_ORDER_NO" class="form-control" /> </td>
                    <td style="text-align:right">材料号</td>
                    <td><input type="text" id="TextBox_MAT_NO" class="form-control" /> </td>
                </tr>

                <tr>
                    <td style="text-align:right">钢种</td>
                    <td>  <input type="text" id="TextBox_SG_SIGN" class="form-control" /> </td>
                    <td style="text-align:right">标准</td>
                    <td><input type="text" id="TextBox_MAT_SPEC_DESC" class="form-control" /> </td>
                </tr>

                <tr>
                    <td style="text-align:right">客户</td>
                    <td>  <input type="text" id="TextBox_CUSTOMER_CODE" class="form-control" /> </td>
                    <td style="text-align:right">下载</td>
                    <td>
                        <select id="select_DELIVY_STATUS" class="form-select">
                            <option value="0" selected="selected">未下载</option>
                            <option value="1">已下载</option>
                            <option value="n"></option>
                        </select>


                    </td>
                </tr>




                <tr>
                    <td style="text-align:center;height:60px;" colspan="4">
                        <button ID="btnLoadData" type="button" onclick="Inq_btn(this); return false;" class="input_btn">查询</button>
                    </td>
                </tr>



            </table>


            <div class="error-message" id="errorMessage"></div>

            <!--微信端批量下载功能不是很友好，无法展示进度条，需要跳转，跳转本身有安全隐患-->
            <div class="control-panel" style="display:none">
                <div class="batch-control">
                    <input type="checkbox" id="selectAll" class="select-all">
                    <label for="selectAll">全选</label>
                    <span>已选择 <span id="selectedCount">0</span> 个文件</span>
                </div>
                <button id="batchDownloadBtn" type="button" class="batch-download-btn" disabled>批量下载</button>
            </div>




            <!--<div id="msg_note">
                <asp:Label ID="Label_note" runat="server" Text="Label"></asp:Label>
            </div>-->

            <div id="dataContainer">
            </div> <!-- 数据将插入到这里 -->

        </div>
    </form>
    <script src="./js/jquery-3.6.0.min.js"></script>

    <script src="js/fileDownloader.js"></script>
    <script type="text/javascript">

         


        // 配置下载器
        const downloader = new FileDownloader({
            apiBaseUrl: '/api/files',
            timeout: 0
        });





        const apiBaseUrl = '/api'; // 修改为后端地址和端口

        // 存储文件数据
        let files = [];//数组；
        let selectedFiles = new Set();//Set 是 JavaScript 中的一种内置集合类型，用于存储唯一值的集合；效率高于数组


        // DOM元素
        const fileList = document.getElementById('dataContainer');
        const selectAll = document.getElementById('selectAll');
        const selectedCount = document.getElementById('selectedCount');
        const batchDownloadBtn = document.getElementById('batchDownloadBtn');
        const errorMessage = document.getElementById('errorMessage');



        $(document).ready(function () {
            // 检查 sessionStorage 是否有数据

            if (sessionStorage.getItem('dataSet_tqmcc801')) {
                var data = JSON.parse(sessionStorage.getItem('dataSet_tqmcc801'));
                loadTableData(data["tqmcc801"]);
                files = data["tqmcc801"];
                Inq_btn(null);
            }

        });


        // 初始化
        async function Inq_btn(button) {

            //查询数据+ 渲染文件
            if (button != null) {
                await InqData(button);
            }

            // 全选/取消全选
            selectAll.addEventListener('change', function () {

                const checkboxes = document.querySelectorAll('.file-checkbox');



                checkboxes.forEach(checkbox => {
                    checkbox.checked = this.checked;

                    const fileGuid = checkbox.dataset.fileGuid;

                    const file_pound_no = checkbox.dataset.filePound_no;
                    const file_certi_no = checkbox.dataset.fileCerti_no;



                    const select_file = {
                        GUID: fileGuid,
                        POUND_NO: file_pound_no,
                        CERTI_NO: file_certi_no

                    };

                    if (this.checked) {
                        //console.log("46----------[");
                        // selectedFiles.add(tableRecord);
                        selectedFiles.add(JSON.stringify(select_file, Object.keys(select_file).sort()));
                    }
                    else {
                        selectedFiles.delete(JSON.stringify(select_file, Object.keys(select_file).sort()));
                        // selectedFiles.delete(tableRecord);
                        //console.log("48----------[");
                    }
                });

                updateSelectionInfo();


            });

            // 批量下载
            batchDownloadBtn.addEventListener('click', downloadBatchFiles);
        }

        //查询数据+ 渲染文件
        async function InqData(button) {

            // 显示加载动画
            var loadingElement = document.getElementById('loading');
            loadingElement.style.display = 'block';
            button.disabled = true;


            var pound_no = document.getElementById("TextBox_pound_no").value;
            var wagon_no = document.getElementById("TextBox_wagon_no").value;
            var order_no = document.getElementById("TextBox_ORDER_NO").value;
            var mat_no = document.getElementById("TextBox_MAT_NO").value;

            const select = document.getElementById('select_DELIVY_STATUS');
            const delivy_status = select.value; // 获取代码值




            //可能隐藏；
            var sg_sign = "";
            var mat_spec_desc = "";
            var customer_code = "";//客户名称


            var TextBox_sg_sign = document.getElementById("TextBox_SG_SIGN");
            var TextBox_mat_spec_desc = document.getElementById("TextBox_MAT_SPEC_DESC");
            var TextBox_CUSTOMER_CODE = document.getElementById("TextBox_CUSTOMER_CODE");






            if (TextBox_sg_sign != null) {
                sg_sign = TextBox_sg_sign.value;
            }
            if (TextBox_mat_spec_desc != null) {
                mat_spec_desc = TextBox_mat_spec_desc.value;
            }
            if (TextBox_CUSTOMER_CODE != null) {
                customer_code = TextBox_CUSTOMER_CODE.value;
            }


            const TableData1 = [
                {
                    pound_no: pound_no
                    , wagon_no: wagon_no
                    , order_no: order_no
                    , mat_no: mat_no
                    , delivy_status: delivy_status
                    , sg_sign: sg_sign
                    , mat_spec_desc: mat_spec_desc
                    , customer_code: customer_code
                    , REMARK: "oTHJ_wu0mFAdMSniwygWWO3164uI"
                }
            ];

            const PageInfoData = [
                {
                    recordFrom: 0 //记录在数据库中的起始号：一般为(int.Parse(page_no) - 1) * int.Parse(page_size)
                    , pageSize: 30 //记录数，一般 //int.Parse(pageSize)
                }
            ];

            //2.构建符合DataSet格式的JSON（仅包含table0表）
            const requestData = {
                Table1: TableData1  // 表名唯一即可，建议统一Table1，值为行数据数组
                , PageInfo: PageInfoData  // 表名固定为PageInfo，分页数据
            };

            try {
                const response = await fetch(`${apiBaseUrl}/Index/Post2`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(requestData)
                });



                //response.status<400时response.ok true;当response.status>=400 true;
                if (!response.ok) {


                    const error = await response.json();

                    if (response.status == "401") {
                        window.location.href = error.authUrl;
                    }

                    throw new Error(error.message || '查询失败2');


                }

                // 隐藏加载动画
                loadingElement.style.display = 'none';
                button.disabled = false;


                var JsonData = await response.json();



                sessionStorage.setItem('dataSet_tqmcc801', JSON.stringify(JsonData));

                //当前查询的总数据；
                files = JsonData["tqmcc801"];

                //加载数据；
                loadTableData(JsonData["tqmcc801"]);




            } catch (error) {
                // 隐藏加载动画
                loadingElement.style.display = 'none';
                button.disabled = false;

                // 清空现有数据
                var dataContainer = $('#dataContainer');
                dataContainer.empty();

                showError('错误: ' + error.message);
            }




        }


        // 渲染文件列表
        function loadTableData(data) {
            var dataContainer = $('#dataContainer');
            dataContainer.empty(); // 清空现有数据

            if (Array.isArray(data)) {
                let lastCategory = null; // 用于跟踪上一个类别

                let i = 1;
                $.each(data, function (index, item) {


                    var recordtopDiv = $('<div class="record-top"></div>');



                    // 判断当前行的 Category 是否与上一行相同
                    if (lastCategory != item.POUND_NO) {

                        i = 1;
                        recordtopDiv.append('<span class="item-id1A">磅单: ' + item.POUND_NO + '</span>');
                        recordtopDiv.append('<span class="item-id1B">' + item.WAGON_NO + '</span>');
                        recordtopDiv.append('<span class="item-id1B">' + item.NET_WT_TIME + '</span>');
                        // 如果相同，则隐藏当前类别
                        //recordDiv.append('<span class="hidden">磅单号: ' + item.POUND_NO + '</span>');

                        recordtopDiv.append('<div class="item_last"></div>');

                        dataContainer.append(recordtopDiv);



                        lastCategory = item.POUND_NO;

                    }
                    else {
                        // 如果不同，则显示当前类别

                        // 更新上一个类别为当前类别

                        i = i + 1;
                    }

                    var recordbotDiv = $('<div class="record-bot"></div>');


                    //recordbotDiv.append('<span class="item-id2A">质保书 ' + i + ':' + item.SG_SIGN + '，' + item.SG_STD + '</span>');
                    recordbotDiv.append('<span class="item-id2A"><input type="checkbox" class="file-checkbox" style="display:none" data-file-guid=' + item.GUID + ' data-file-pound_no=' + item.POUND_NO + ' data-file-certi_no=' + item.CERTI_NO + '>质保书' + i + ' :' + item.SG_SIGN + '</span>');


                    // 添加超链接列
                    // recordbotDiv.append('<span class="item-id2B"><a href="../excel_to_pdf.aspx?pound_no=' + item.POUND_NO + '&certi_no=' + item.CERTI_NO + '&guid=' + item.GUID + '&pro_type=V" class="item-id2">预览</a></span>');

                    recordbotDiv.append('<span class="item-id2B"><button  type="button" class="viewload-btn" >预览</button></span>');

                    recordbotDiv.append('<span class="item-id2B"><button  type="button" class="download-btn" data-file-id=' + item.CERTI_NO + '>下载(' + item.DOWN_NUM + ')</button></span>');




                    // 添加超链接列
                    //recordbotDiv.append('<a href="excel_to_pdf.aspx?pound_no=' + item.POUND_NO + '&certi_no=' + item.CERTI_NO + '&guid=' + item.GUID + '&pro_type=D" class="item-id2">质保书下载</a>');



                    //recordbotDiv.append('<div class="item_last"></div>');


                    dataContainer.append(recordbotDiv);
                    dataContainer.append('<div class="item_last"></div>');






                    // 单个下载按钮事件
                    // const downloadBtn = recordbotDiv.querySelector('.download-btn');
                    //downloadBtn.addEventListener('click', function () {
                    //    downloadSingleFile(item.POUND_NO, item.GUID);
                    //});


                    // 复选框事件
                    const checkbox = recordbotDiv.find('.file-checkbox');
                    checkbox.on('change', function () {
                        const select_file = {
                            GUID: item.GUID,
                            POUND_NO: item.POUND_NO,
                            CERTI_NO: item.CERTI_NO
                        };


                        if (this.checked) {
                            //selectedFiles.add(item.GUID);


                            //selectedFiles.add(JSON.stringify(select_file));
                            //对json中key进行排序，及时json格式不同也无所谓的；
                            selectedFiles.add(JSON.stringify(select_file, Object.keys(select_file).sort()));
                        }
                        else {


                            //不是数组；
                            //const indexToRemove = selectedFiles.findIndex(file => file.GUID === item.GUID);
                            //if (indexToRemove != -1) {
                            //    selectedFiles.splice(indexToRemove,1)
                            //}
                            selectedFiles.delete(JSON.stringify(select_file, Object.keys(select_file).sort()));


                            //selectedFiles.push(tableRecord);
                            //selectedFiles.delete(item.GUID);
                            selectAll.checked = false;
                        }

                        //console.log("selectedFiles.size:[" + selectedFiles.size+"]");

                        //selectedFiles.forEach(user => {
                        //    //console.log(`${user.GUID} - ${user.POUND_NO}`);
                        //});

                        for (const user of selectedFiles) {
                            console.log(user);
                        }


                        updateSelectionInfo();
                    });


                    const downloadBtn = recordbotDiv.find('.download-btn');
                    downloadBtn.on('click', function () {
                        downloadSingleFile(item.POUND_NO, item.GUID, item.CERTI_NO);
                    });


                    const viewloadBtn = recordbotDiv.find('.viewload-btn');
                    viewloadBtn.on('click', function () {
                        viewloadSingleFile(item.POUND_NO, item.GUID, item.CERTI_NO);
                    });



                });


            } else {

                showError("数据格式不正确" + data);

            }
        }

        // 单下载文件
        async function downloadSingleFile(POUND_NO, GUID, CERTI_NO) {

            //alert("downloadSingleFile:" + POUND_NO);


            // //console.log("------------------------------------------------");

            // //console.error("POUND_NO:" + POUND_NO);
            // //console.error("POUND_NO:", POUND_NO);

            const params = {
                POUND_NO: POUND_NO,
                GUID: GUID,
                CERTI_NO: CERTI_NO

            };


            try {


                const result = await downloader.download(POUND_NO, GUID, CERTI_NO, {
                    method: 'POST',
                    showProgress: true
                });
                console.log('下载结果:', result);



                //const response = await fetch(`${apiBaseUrl}/files/download/single`, {
                //    method: 'POST',
                //    headers: {
                //        'Content-Type': 'application/json',
                //    },
                //    body: JSON.stringify(simpleData)
                //});

                //if (!response.ok) {
                //    const error = await response.json();
                //    throw new Error(error.message || '下载失败');
                //}



                //// 获取文件名
                //const contentDisposition = response.headers.get('Content-Disposition');
                //let fileName = `download_${GUID}.pdf`;


                ////若后台返回文件名，则用后台的文件名称；
                //if (contentDisposition) {
                //    let match = contentDisposition.match(/filename\*=utf-8''([^;]+)/i);
                //    if (match) {
                //        fileName = decodeURIComponent(match[1]);
                //    }
                //    else {
                //        match = contentDisposition.match(/filename=([^;]+)/i);
                //        if (match) {
                //            // 移除可能的引号并处理编码
                //            fileName = match[1].trim().replace(/^"|"$/g, '')
                //        }
                //    }
                //}
                //////console.log("6------------------------------------------------2");


                //// 创建Blob并下载
                //const blob = await response.blob();

                //// 检测微信环境
                //const isWeChat = /MicroMessenger/i.test(navigator.userAgent);

                //alert("isWeChat:[" + isWeChat);
                //alert("response:[" + response);


                //const downloadUrl = `${apiBaseUrl}/files/download/single?${params}`;


                //alert("1-------------downloadUrl:[" + downloadUrl);
                //// 微信环境直接打开新窗口
                //if (/MicroMessenger/i.test(navigator.userAgent)) {
                //    alert("2-------------downloadUrl:[" + downloadUrl);

                //    window.open(downloadUrl, '_blank');
                //}
                //else
                //{
                //    alert("3-------------downloadUrl:[" + downloadUrl);

                //    const a = document.createElement('a');
                //    a.href = downloadUrl;
                //    a.download = 'file.pdf';
                //    document.body.appendChild(a);
                //    a.click();
                //    document.body.removeChild(a);

                //    //const url = window.URL.createObjectURL(blob);
                //    //const a = document.createElement('a');
                //    //a.href = url;
                //    //a.download = fileName;
                //    //document.body.appendChild(a);
                //    //a.click();
                //    //document.body.removeChild(a);
                //    //window.URL.revokeObjectURL(url);
                //}

                // 更新下载次数显示
                await updateDownloadCountDisplay(CERTI_NO);

            }
            catch (error) {
                showError('下载失败: ' + error.message);
            }
        }

        // 单文件预览
        async function viewloadSingleFile(POUND_NO, GUID, CERTI_NO) {

            try {

                const result = await downloader.viewload(POUND_NO, GUID, CERTI_NO, {
                    method: 'POST',
                    showProgress: true
                });
                console.log('预览结果:', result);

            }
            catch (error) {
                showError('下载失败: ' + error.message);
            }
        }



        // 批量下载文件
        async function downloadBatchFiles() {
            if (selectedFiles.size === 0) return;

            // 显示加载动画
            var loadingElement = document.getElementById('loading');
            loadingElement.style.display = 'block';
            batchDownloadBtn.disabled = true;


            const fileIds = Array.from(selectedFiles);
            //body: JSON.stringify({ fileIds: fileIds })
            try {
                const response = await fetch(`${apiBaseUrl}/files/download/batch`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(fileIds)
                });


                console.log("response.ok:" + response.ok);


                if (!response.ok) {
                    const error = await response.json();
                    throw new Error(error.message || '批量下载失败');
                }

                // 隐藏加载动画
                loadingElement.style.display = 'none';
                batchDownloadBtn.disabled = false;


                // 获取内容类型和文件名
                const contentType = response.headers.get('Content-Type');
                const contentDisposition = response.headers.get('Content-Disposition');
                let fileName = `batch_download_${Date.now()}.zip`;


                if (contentDisposition) {
                    let match = contentDisposition.match(/filename\*=utf-8''([^;]+)/i);
                    if (match) {
                        fileName = decodeURIComponent(match[1]);
                    }
                    else {
                        match = contentDisposition.match(/filename=([^;]+)/i);
                        if (match) {
                            // 移除可能的引号并处理编码
                            fileName = match[1].trim().replace(/^"|"$/g, '')
                        }
                    }
                }


                const isWeChat = /MicroMessenger/i.test(navigator.userAgent);

                console.log("isWeChat:" + isWeChat);

                const blob = await response.blob();
                if (isWeChat) {

                    // 方案1: 尝试在新窗口打开
                    //const url = window.URL.createObjectURL(blob);
                    //const newWindow = window.open(url, '_blank');


                    const mimeType = "application/pdf";//blob.type || getMimeType(fileName); // 兜底 MIME 类型
                    const blobWithType = new Blob([blob], { type: mimeType });

                    // 2. 创建 <a> 标签
                    const a = document.createElement('a');
                    // 3. 生成 Blob URL（和原逻辑一致，但通过 <a> 触发）
                    a.href = window.URL.createObjectURL(blobWithType);
                    // 4. 指定下载文件名（关键：避免文件名为随机字符串）
                    a.download = fileName; // 例如：'导出数据.xlsx'
                    // 5. 隐藏标签并触发点击
                    a.style.display = 'none';
                    document.body.appendChild(a);
                    a.click();

                    // 6. 清理资源（避免内存泄漏）
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(a.href);



                }
                else {
                    // 创建Blob并下载

                    const url = window.URL.createObjectURL(blob);

                    console.log("url:" + url);

                    const a = document.createElement('a');
                    a.href = url;
                    a.download = fileName;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                }












                // 更新所有选中文件的下载次数显示
                for (const fileId of fileIds) {
                    var certi_no_js = JSON.parse(fileId);
                    // //console.log("certi_no_js:" + certi_no_js);
                    await updateDownloadCountDisplay(certi_no_js.CERTI_NO);
                }

                // 清空选择
                selectedFiles.clear();
                updateSelectionInfo();
                document.querySelectorAll('.file-checkbox').forEach(cb => cb.checked = false);

            } catch (error) {
                console.log("error.message:" + error.message);
                showError('批量下载失败: ' + error.message);
                // 隐藏加载动画
                loadingElement.style.display = 'none';
                batchDownloadBtn.disabled = false;
            }
        }

        // 更新选择信息
        function updateSelectionInfo() {


            selectedCount.textContent = selectedFiles.size;
            batchDownloadBtn.disabled = selectedFiles.size === 0;

            console.log("[1----------]" + selectedFiles.size);
            console.log("[2----------]" + files.length);


            selectAll.checked = selectedFiles.size === files.length && files.length > 0;
        }

        // 更新下载次数显示
        async function updateDownloadCountDisplay(certi_no) {
            const TableData1 = [
                {
                    ITEM_SEQ: 18861306
                    , CERTI_NO: certi_no
                }
            ];


            // 2. 构建符合DataSet格式的JSON（仅包含table0表）
            const requestData = {
                INQ: TableData1
            };


            try {
                const response = await fetch(`${apiBaseUrl}/files/download/get_num`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(requestData)
                });

                if (response.ok) {
                    const inDataSet = await response.json();



                    var down_num = 0;
                    if (inDataSet["SYS"][0]["FLAG"] == "0"
                        && inDataSet["Table0"].length > 0
                    ) {
                        down_num = inDataSet["Table0"][0]["PRINT_NUM"];
                    }



                    //  const fileElementA = document.querySelector(`[data-file-id="LT25A30145LT2580154006"]`);


                    const fileElement = document.querySelector(`[data-file-id="${certi_no}"]`);




                    if (fileElement) {

                        fileElement.textContent = `下载(${down_num})`;
                        // 当前对象fileElement的付对象closest下的.download-count对象；即兄弟对象；
                        //const countElement = fileElement.closest('.file-item').querySelector('.download-count');

                        //当前对象fileElement下的子对象.download-count
                        const countElementB = fileElement.querySelector('.download-count');
                        //if (countElement) {
                        //    countElement.textContent = `下载(${down_num})`;
                        //}
                    }
                }
            }
            catch (error) {
                //console.error('更新下载次数显示失败:', error);
            }
        }

        // 显示错误信息-------------------------
        function showError(message) {
            errorMessage.textContent = message;
            errorMessage.style.display = 'block';
            setTimeout(() => {
                errorMessage.style.display = 'none';
            }, 5000);
        }








    </script>
</body>
</html>